
package com.shop.cloud.upms.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.common.core.util.SensitiveUtils;
import com.shop.cloud.common.log.annotation.SysLog;
import com.shop.cloud.common.security.annotation.Inside;
import com.shop.cloud.upms.common.entity.SysConfigSms;
import com.shop.cloud.upms.admin.service.SysConfigSmsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

/**
 * 短信配置
 *
 * @author
 * @date 2022-09-09 14:33:35
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/configsms")
@Tag(description = "configsms", name = "短信配置管理")
public class SysConfigSmsController {

    private final SysConfigSmsService sysConfigSmsService;

    /**
     * 短信配置修改
     * @param sysConfigSms 短信配置
     * @return R
     */
    @Operation(summary = "短信配置修改")
    @SysLog("修改短信配置")
    @PutMapping
    @PreAuthorize("@ato.hasAuthority('sys:configsms:edit')")
    public R updateById(@RequestBody SysConfigSms sysConfigSms) {
		if(StrUtil.isNotBlank(sysConfigSms.getId())){
			//数据脱敏
			SysConfigSms sysConfigSmsOld = sysConfigSmsService.getById(sysConfigSms.getId());
			String accessKeySecret = sysConfigSmsOld.getAccessKeySecret();
			if(StrUtil.isNotBlank(accessKeySecret)){
				String sensitiveAccessKeySecret = SensitiveUtils.process(accessKeySecret);
				if(!sensitiveAccessKeySecret.equals(sysConfigSms.getAccessKeySecret())){
					accessKeySecret = sysConfigSms.getAccessKeySecret();
				}
				sysConfigSms.setAccessKeySecret(accessKeySecret);
			}

			sysConfigSmsService.updateById(sysConfigSms);
			return R.ok(sysConfigSms);
		}else{
			sysConfigSmsService.save(sysConfigSms);
			return R.ok(sysConfigSms);
		}
    }

	/**
	 * 查询短信配置
	 * @return R
	 */
	@Operation(summary = "查询短信配置")
	@GetMapping()
	@PreAuthorize("@ato.hasAuthority('sys:configsms:get')")
	public R get() {
		SysConfigSms sysConfigSms = sysConfigSmsService.getOne(Wrappers.emptyWrapper());
		if(sysConfigSms != null){
			//数据脱敏
			String sensitiveSecret = SensitiveUtils.process(sysConfigSms.getAccessKeySecret());
			sysConfigSms.setAccessKeySecret(sensitiveSecret);
		}

		return R.ok(sysConfigSms);
	}

	/**
	 * 查询短信配置（服务间调用）
	 * @return R
	 */
	@Inside
	@Operation(summary = "短信配置查询")
	@GetMapping("/inside")
	public R getInside() {
		return R.ok(sysConfigSmsService.getOne());
	}
}
